/**
 * Wihidum - Efficient Broker Hierarchy for Publish Subscribe Middleware
 *
 * License      :   Apache License 2.0
 * Home Page    :   http://code.google.com/p/wihidum/
 * Mailing List :   wihidum@googlegroups.com
 */
package lk.mrt.cse.wihidum.storage;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import java.util.ArrayList;
import java.util.List;

public class MessageTraceDAO implements MessageTraceManager {

    Session session = null;
    private static final Logger logger = Logger.getLogger(MessageTraceDAO.class);

    public MessageTraceDAO() {
        this.session = DataBaseManager.getSessionFactory().getCurrentSession();
    }

    public boolean saveMessageTrace(MessageTrace messageTrace) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(messageTrace);
            tx.commit();
            logger.info("Message trace saved successfully");
            return true;
        }
        catch (HibernateException ex) {
            logger.error("Error in saving message trace", ex);
            return false;
        }
    }

    public boolean deleteMessageTrace(MessageTrace messageTrace) {
        try {
            Transaction tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(MessageTrace.class)
                    .add(Restrictions.eq("id", messageTrace.getId()));
            ArrayList<MessageTrace> searchedList = (ArrayList<MessageTrace>) criteria.list();
            MessageTrace m = searchedList.get(0);
            session.delete(m);
            tx.commit();
            logger.info("Message trace deleted successfully");
            return true;
        }
        catch (HibernateException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public List<MessageTrace> getMessageTraces() {
        try {
            session.beginTransaction();
            Criteria criteria = session.createCriteria(Broker.class);
            return (ArrayList<MessageTrace>) criteria.list();
        }
        catch (HibernateException ex) {
            ex.printStackTrace();
            return new ArrayList<MessageTrace>();
        }
    }
}
